﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Logging;
using Microsoft.Phone.Controls;
using System.Threading.Tasks;
using Microsoft.Phone.Scheduler;
using Microsoft.Phone.Shell;
using Newtonsoft.Json.Linq;

namespace AutoSigner
{
    public partial class MainPage : PhoneApplicationPage
    {
        private const string TaskName = "KLive";
        private const string StringInstallTask = "安装签到服务";
        private const string StringUninstallTask = "卸载签到服务";

        private Logging.DataBase _dataBaseContext = new DataBase();

        private bool _agentInstalled;
        // Constructor
        public MainPage()
        {
            InitializeComponent();

            this.button1.Content = IsAgentInstalled ? StringUninstallTask : StringInstallTask;
            GetState();
            LoadLog();

            this.Loaded += OnLoaded;
        }

        private async void OnLoaded(object sender, RoutedEventArgs args)
        {   


        }

        private async void LoadLog()
        {
            var logs = (from log in _dataBaseContext.Logs orderby log.LogTime descending select log).Take(10);
            this.listBox1.ItemsSource = logs;
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            if (IsAgentInstalled)
            {
                UninstallTask();
                button1.Content = StringInstallTask;
            }
            else
            {
                InstallTask();
                button1.Content = StringUninstallTask;
                MessageBox.Show("服务安装成功");
            }
        }

        private void InstallTask()
        {
            UninstallTask();
            var task = new PeriodicTask(TaskName);
            task.Description = "快盘签到任务";
            ScheduledActionService.Add(task);

#if DEBUG
            ScheduledActionService.LaunchForTest(TaskName, new TimeSpan(0,0,1));
#endif

        }

        private void UninstallTask()
        {
            if (ScheduledActionService.Find(TaskName) != null)
            {
                ScheduledActionService.Remove(TaskName);
            }
        }

        private bool IsAgentInstalled
        {
            get { return FindTask() != null; }
        }

        private ScheduledAction FindTask()
        {
            return ScheduledActionService.Find(TaskName);
        }

        private void GetState()
        {
            var tsk = (PeriodicTask)FindTask();
            if (tsk != null)
            {
                if (tsk.LastScheduledTime != DateTime.MinValue)
                {
                    this.button2.Content += "(上次签到 - " + tsk.LastScheduledTime.ToString("HH:mm") + ")";
                }

            }
        }

        private async void button2_Click(object sender, RoutedEventArgs e)
        {
            var msg = string.Empty;

            try
            {
                var progress = new ProgressIndicator() { IsIndeterminate = true, IsVisible = true };
                SystemTray.ProgressIndicator = progress;
                this.button2.IsEnabled = false;
                var res = await BackgroundSigner.SignService.SignAsync();
                msg = res.ToString();
            }
            catch (Exception ex)
            {
                msg = ex.Message;
            }
            finally
            {
                button2.IsEnabled = true;
                SystemTray.ProgressIndicator = null;
                MessageBox.Show(msg);

            }
        }

        private void button3_Click(object sender, RoutedEventArgs e)
        {
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            //object id;
            //if (!Microsoft.Phone.Shell.PhoneApplicationService.Current.State.TryGetValue("id", out id))
            //{
            //    MessageBox.Show("第一次运行，请输入用户Id");
            //    NavigationService.Navigate(new Uri("/Settings.xaml", UriKind.RelativeOrAbsolute));
            //}
        }

        private void ApplicationBarIconButton_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/Settings.xaml", UriKind.RelativeOrAbsolute));
        }

        private void ApplicationBarIconButton_Click_1(object sender, EventArgs e)
        {
             _dataBaseContext.Logs.DeleteAllOnSubmit(_dataBaseContext.Logs);
            _dataBaseContext.SubmitChanges();
            this.listBox1.ItemsSource = null;

        }
    }
}